# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Permission(models.Model):
    """权限模型 - 模仿若依权限管理"""
    _name = 'device.permission'
    _description = '权限管理'
    _order = 'sequence, name'
    _parent_name = "parent_id"
    _parent_store = True
    _rec_name = 'complete_name'
    
    name = fields.Char('权限名称', required=True)
    complete_name = fields.Char('完整名称', compute='_compute_complete_name', recursive=True, store=True)
    code = fields.Char('权限编码', required=True)
    permission_type = fields.Selection([
        ('M', '目录'),
        ('C', '菜单'),
        ('F', '按钮')
    ], string='权限类型', required=True)
    
    # 父级权限
    parent_id = fields.Many2one('device.permission', '父级权限', ondelete='cascade')
    parent_path = fields.Char(index=True)
    child_ids = fields.One2many('device.permission', 'parent_id', '子权限')
    
    # 菜单相关
    menu_path = fields.Char('路由地址')
    component = fields.Char('组件路径')
    icon = fields.Char('菜单图标')
    
    # 按钮相关
    perms = fields.Char('权限标识', help='前端权限标识，如：system:user:list')
    
    # 基础信息
    sequence = fields.Integer('排序', default=10)
    visible = fields.Boolean('显示状态', default=True, help='是否在菜单中显示')
    status = fields.Boolean('菜单状态', default=True, help='是否启用')
    
    # 外链
    is_frame = fields.Boolean('是否外链', default=False)
    
    # 缓存
    is_cache = fields.Boolean('是否缓存', default=False)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Many2one('res.users', '创建者', default=lambda self: self.env.user)
    update_by = fields.Many2one('res.users', '更新者', default=lambda self: self.env.user)
    
    @api.depends('name', 'parent_id.complete_name')
    def _compute_complete_name(self):
        for permission in self:
            if permission.parent_id:
                permission.complete_name = f"{permission.parent_id.complete_name} / {permission.name}"
            else:
                permission.complete_name = permission.name
    
    @api.constrains('code')
    def _check_code_unique(self):
        for record in self:
            if self.search_count([('code', '=', record.code), ('id', '!=', record.id)]) > 0:
                raise ValidationError(f'权限编码 {record.code} 已存在，请使用其他编码。')
    
    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError('不能创建循环的层级关系。')
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        vals['update_by'] = self.env.user.id
        return super().write(vals)
    
    def get_children_permissions(self):
        """获取所有子权限"""
        return self.search([('parent_path', '=like', self.parent_path + '%')])
